package algorithm.linked;

import org.junit.Test;

public class LinkedDemo {

  @Test
  public void test() {

    ListNode parent = new ListNode(90);
    parent.next = new ListNode(100);

    ListNode a = new ListNode(5);
    a.next = new ListNode(20);
    a.next.next = parent;

    ListNode b = new ListNode(30);
    b.next = new ListNode(35);
    b.next.next = new ListNode(40);
    b.next.next.next = parent;

    ListNode parent1 = getParent(a, b);
    System.out.println(parent1);

  }

  public ListNode getParent(ListNode a, ListNode b) {
    ListNode ahead = a;
    ListNode bhead = b;

    ListNode aindex = a;
    ListNode bindex = b;

    while (aindex != bindex) {
      aindex = aindex.next;
      if(aindex == null) aindex = bhead;

      bindex = bindex.next;
      if(bindex == null) bindex = ahead;
    }


    return aindex;
  }

}
